<template>
<div>
  <!--<div class="crumbs">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item><i class="el-icon-setting"></i> 系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>{{$route.meta.displayName}}</el-breadcrumb-item>
    </el-breadcrumb>
  </div>-->
  <el-row :gutter="10" type="flex" class="row-bg" justify="space-between">
    <el-col :span="14">
      <el-button-group>
        <el-button type="primary" icon="plus" @click="addClick()">新增告警</el-button>
      </el-button-group>
    </el-col>
    <el-col :span="10">
      <el-input v-model="input" placeholder="请输入关键字" style="float:right;width:300px" size='small' icon="search" @change="inputChangeAction"></el-input>
    </el-col>
  </el-row>

  <el-table :data="tableData" height='600' style="width: 100%" @row-dblclick="editClick">
    <el-table-column label="告警名称" prop="name">
    </el-table-column>
    <el-table-column label="运行状态" prop="status">
      <template scope="scope">
              <el-popover trigger="hover" placement="right">
                <p>点击停用/启用告警</p>
              <el-button slot="reference" type="success" v-if="scope.row.status ==0" @click="updateStatus(tableData[scope.$index])">已启用</el-button>
              <el-button slot="reference" type="danger" v-if="scope.row.status ==1" @click="updateStatus(tableData[scope.$index])">停用的</el-button>
            </el-popover>
</template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template scope="scope">
<el-button-group>
  <el-button @click.native.prevent="editClick(tableData[scope.$index])" icon="edit" type="primary" size="small">
  </el-button>
  <el-button @click="deleteClick(scope.$index,tableData)" icon="delete" type="primary" size="small"></el-button>
</el-button-group>
</template>
      </el-table-column>
    </el-table>
    <el-dialog title="告警设置" v-model="dialogSetVisible">
          <el-button type="primary" icon="check" @click="saveGraphs()" size='small'>保存</el-button>

            <el-tabs v-model="activeName" >
              <el-tab-pane label="告警条件" name="first">
                <el-form :model="setForm" :rules="rules" ref="setForm" >

                  <el-form-item label="告警名称" prop="name">
                    <el-input v-model="setForm.name"></el-input>
                  </el-form-item>
                  <el-form-item label="" prop="status">
                    <el-checkbox v-model="setForm.status" true-label="0" false-label="1">是否启用</el-checkbox>
                  </el-form-item>

                  <el-form-item label="条件组合表达式" prop="eval_formula">
                    <el-input v-model="setForm.eval_formula"></el-input>
                  </el-form-item>

                  <el-form-item label="">
                    <el-button-group>
                      <el-button type="primary" icon="plus" @click="addCondition()" size ="small">新增条件</el-button>
                    </el-button-group>
                  </el-form-item>

                  <el-form-item label="">
                    <el-table :data="conditionData" height="200" @row-dblclick="editCondition">
                      <el-table-column label="标签" prop="formulaid">
                      </el-table-column>
                      <el-table-column label="条件">
                        <template scope="scope">
                          <span>{{conditionFormartter(conditionData[scope.$index])}}</span>
                        </template>
                      </el-table-column>
                      <el-table-column
                          fixed="right"
                          label="操作">
                          <template scope="scope">
                              <el-button-group>
                                <el-button type="primary" icon="edit" size="small" @click="editCondition(conditionData[scope.$index])"></el-button>
                                <el-button type="primary" icon="delete" size="small" @click="deleteCondition(conditionData[scope.$index])"></el-button>
                              </el-button-group>
                          </template>
                      </el-table-column>
                      </el-table>
                  </el-form-item>

                </el-form>
              </el-tab-pane>
              <el-tab-pane label="告警方式" name="second">
                <el-form :model="setForm" :rules="rules" ref="setForm" >

                  <el-form-item label="告警方式" prop="name">
                    <el-checkbox-group v-model="sendList" @change="checkChange">
                      <el-checkbox v-for="city in sendTyps" :label="city" :key="city">{{city}}</el-checkbox>
                    </el-checkbox-group>
                  </el-form-item>
                  <el-tabs v-model="currentSendTabName" type="card" closable @tab-remove="removeTab">
                    <el-tab-pane
                      v-for="(item, index) in sendTabs"
                      :key="item.name"
                      :label="item.title"
                      :name="item.name"
                    >

                    </el-tab-pane>
                    <component :is="currentView" transition="fade" transition-mode="out-in" keep-alive></component>
                  </el-tabs>


                </el-form>
              </el-tab-pane>
            </el-tabs>
    </el-dialog>
    <el-dialog title="告警条件" v-model="dialogConditionVisible">
      <el-form :model="conditionForm" :rules="conditionRules" ref="conditionForm" >

        <el-form-item prop="conditiontype">
          <el-select v-model="conditionForm.conditiontype" @change="conditionTypeChange" ref="conditionData.conditiontype"  placeholder="条件分类">
            <el-option
              v-for="item in conditionTypeClassify"
              :label="item.label"
              :value="item.value"
              :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="operator">
          <el-select v-model="conditionForm.operator" ref="conditionData.operator"  placeholder="运算符">
            <el-option
              v-for="item in operatorClassify"
              :label="item.label"
              :value="item.value"
              :key="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="valueName">
          <el-select v-if="conditionForm.conditiontype=='4'" v-model="conditionForm.value" ref="conditionData.value"  placeholder="触发器级别">
            <el-option
              v-for="item in triggerClassify"
              :label="item.label"
              :value="item.value"
              :key="item.id">
            </el-option>
          </el-select>
          <el-input v-else="conditionForm.conditiontype=='4'" v-model="conditionForm.valueName" placeholder="请输入条件值" size='small' icon="search"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" icon="check" @click="saveCondition()" size='small'>确定</el-button>
    </el-dialog>
  </div>
</template>

<script>
import api from '../../api/alarm.js'
import ResTypeEnum from '../../common/resTypeEnum'
import emailCompoent from './set/email.vue'
import msgCompoent from './set/msg.vue'
import wchatCompoent from './set/wchat.vue'
import undefineCompoent from './set/undefine.vue'
export default {
  components: {
    emailCompoent
  },
  data: function() {
    return {
      tableData: [],
      conditionData: [],
      setForm: {
        grsName: '',
        grsNo: '',
        remark: '',
        status: '',
        eval_formula: ''
      },
      conditionForm: {
        conditiontype: "",
        operator: "",
        value: "",
        valueName:""
      },
      activeName: 'first',
      input: '',
      sendList: ['邮件'],
      currentSendTabName: '',
      sendTabs: [],
      sendTyps: ['邮件', '短信', '微信'],
      dialogSetVisible: false,
      dialogConditionVisible: false,
      currentView: null,
      rules: {
        name: [{
            required: true,
            message: '请输入告警名称',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 265,
            message: '长度在 3 到 265 个字符',
            trigger: 'blur'
          }
        ]
      },
      conditionRules: {

      },
      conditionTypeClassify: [{
          label: "主机群组",
          value: "0"
        }, {
          label: "主机",
          value: "1"
        },
        {
          label: "触发器",
          value: "2"
        },
        {
          label: "触发器名称",
          value: "3"
        }, {
          label: "触发器示警度",
          value: "4"
        }, {
          label: "时间期间",
          value: "6"
        }
      ],
      conditionAddFlag:true,
      operatorClassify: [],
      triggerClassify:[{
          label: "未分类",
          value: "0"
        }, {
          label: "信息",
          value: "1"
        },
        {
          label: "警告",
          value: "2"
        },
        {
          label: "一般严重",
          value: "3"
        }, {
          label: "严重",
          value: "4"
        }, {
          label: "灾难",
          value: "5"
        }]
    };
  },
  methods: {
    addClick() {
      this.activeName = 'first';
      this.setForm = {
        status: '0'
      };
      this.conditionData = [];
      this.dialogSetVisible = true;
    },
    editClick(row) {
      this.activeName = 'first';
      this.setForm = row;
      this.setForm.eval_formula = row.filter.eval_formula;
      this.conditionData = row.filter.conditions;
      this.dialogSetVisible = true;
    },
    deleteClick(index, row) {
      this.$confirm('是否删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.deletealarms(row[index]["id"]).then((response) => {
          this.queryData();
        }).catch((err) =>{
            console.error(err);
        });
      });
    },
    updateStatus(row) {
      var status = 1 - parseInt(row.status);
      api.upAlarmSetStatus(row.actionid, status).then((response) => {
        this.queryData();
      }).catch((err) =>{
          console.error(err);
      });
    },
    queryData() {
      api.getAlarmSetList().then((response) => {
        var data = response.data;
        this.tableData = data;
      }).catch((err) =>{
          console.error(err);
      });
    },
    openDesigner() {
      $(".rightLayout").show().animate({
        left: "20%"
      }).addClass("showBlock").bind('click', function(e) {
        if (e.stopPropagation) {
          e.stopPropagation();
        } else {
          e.cancelBubble = true;
        }
      });
      //右侧顶部固定
      $(".layoutTop").show().animate({
        left: "20%"
      });
      //隐藏主滚动条，禁止出现双滚，点击其他位置隐藏界面
      $("body").addClass("hideScoll");
    },
    inputChangeAction() {
      var filterData = [];
      var self = this;
      if (this.input == '') {
        this.queryData();
      } else {
        this.tableData = this.tableData.filter(function(v) {
          //遍历行值，如果存在返回该行
          var result = false;
          for (var col in v) {
            if (("" + v[col] + "").indexOf(self.input) >= 0) {
              result = true;
            }
          }
          return result;
        });
      }
    },

    removeTab(targetName) {
      let self = this;
      let tabs = this.sendTabs;
      let activeName;

      tabs.forEach((tab, index) => {
        if (tab.name === targetName) {
          let nextTab = tabs[index + 1] || tabs[index - 1];
          if (nextTab) {
            activeName = nextTab.name;
          }
        }
      });
      let checkList = this.sendList;
      checkList.forEach((check, index) => {
        if (check === targetName) {
          self.sendList.splice(index, 1);
        }
      });

      if (activeName != null) {
        this.currentSendTabName = activeName;
      } else {
        this.currentView = undefineCompoent;
      }
      this.sendTabs = tabs.filter(tab => tab.name !== targetName);
    },
    removeAllTab() {
      this.sendTabs = [];
      this.currentView = undefineCompoent;
    },
    checkChange() {
      this.removeAllTab();
      for (var i = 0; i < this.sendList.length; i++) {
        this.sendTabs.push({
          title: this.sendList[i],
          name: this.sendList[i],
          content: ''
        });

      }
      if (this.currentSendTabName === this.sendList[this.sendList.length - 1]) {
        this.setView();
      } else {
        this.currentSendTabName = this.sendList[this.sendList.length - 1];
      }
    },
    setView() {
      if (this.currentSendTabName == '邮件') {
        this.currentView = emailCompoent;
      } else if (this.currentSendTabName == '短信') {
        this.currentView = msgCompoent;
      } else if (this.currentSendTabName == '微信') {
        this.currentView = wchatCompoent;
      } else {
        this.currentView = undefineCompoent;
      }
    },
    addCondition() {
      this.conditionAddFlag = true;
      this.conditionTypeChange();
      this.dialogConditionVisible = true;
    },
    editCondition(row) {
      this.conditionForm = row;
      this.conditionAddFlag = false;
      this.dialogConditionVisible = true;
    },
    deleteCondition(row) {
      this.conditionForm = row;
      this.conditionAddFlag = false;
      this.dialogConditionVisible = true;
    },
    saveCondition() {
      if(this.conditionAddFlag){
        this.conditionData.push(this.conditionForm);
      }
      this.dialogConditionVisible = false;
    },
    conditionFormartter(row){
        return this.formatterType(row.conditiontype)+" "+this.formatterOperator(row.operator)+" "+this.formatterValue(row);
    },
    formatterType(conditiontype){
      var typeArray= {
           "0": "主机群组",
           "1": "主机",
           "2": "触发器",
           "3": "触发器名称",
           "4": "触发器示警度",
           "6": "时间期间"
        }
        return typeArray[conditiontype];
    },
    formatterOperator(operator){
      var operatorArray= {
           "0": "=",
           "1": "<>",
           "2": "似",
           "3": "不似",
           "4": "在",
           "5": ">=",
           "6": "<=",
           "7": "不在"
        }
        return operatorArray[operator];
    },
    formatterValue(row){
      return row.valueName;
    },
    conditionTypeChange(type) {
      if (type == '0' || type == '1' || type == '2') {
        this.operatorClassify = [{
          label: "=",
          value: '0'
        }, {
          label: "<>",
          value: '1'
        }];
        if(this.conditionForm.operator=='')this.conditionForm.operator='0';
      } else if (type == '3') {
        this.operatorClassify = [{
          label: "似",
          value: '2'
        }, {
          label: "不似",
          value: '3'
        }];
        if(this.conditionForm.operator=='')this.conditionForm.operator='2';
      } else if (type == '4') {
        this.operatorClassify = [{
          label: "=",
          value: '0'
        }, {
          label: "<>",
          value: '1'
        }, {
          label: ">=",
          value: "5"
        }, {
          label: "<=",
          value: "6"
        }];
        if(this.conditionForm.operator=='')this.conditionForm.operator='0';
      } else if (type == '6') {
        this.operatorClassify = [{
          label: "在",
          value: '4'
        }, {
          label: "不在",
          value: '7'
        }];
        if(this.conditionForm.operator=='')this.conditionForm.operator='4';
      }
    }
  },
  mounted: function() {
    this.queryData();
    this.checkChange();
  },
  watch: {
    currentSendTabName() {
      this.setView();
    }
  }
}
</script>


<style>

</style>
